/**
 * @project: parallel-task
 * @package: com.ngplat.paralleltask.utils
 * @filename: ThreadUtils.java
 *
 * Copyright (c) 2018 eSunny Info. Tech Ltd. All rights reserved.
 * 
 */
package com.ngplat.paralleltask.utils;

import java.util.concurrent.ExecutorService;
import java.util.concurrent.TimeUnit;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * @typename: ThreadUtils
 * @brief: 线程相关工具类.
 * @author: KI ZCQ
 * @date: 2018年5月30日 下午8:42:35
 * @version: 1.0.0
 * @since
 * 
 */
public class ThreadUtils {

	private static Logger logger = LoggerFactory.getLogger(ThreadUtils.class);
	
	/**
	 * @Description: sleep等待,单位为毫秒,忽略InterruptedException.
	 * @param millis
	 *            毫秒
	 */
	public static void sleep(long millis) {
		try {
			Thread.sleep(millis);
		} catch (InterruptedException e) {
			// Ignore.
			return;
		}
	}

	/**
	 * @Description: sleep等待,忽略InterruptedException.
	 * @param duration
	 * @param unit
	 */
	public static void sleep(long duration, TimeUnit unit) {
		try {
			Thread.sleep(unit.toMillis(duration));
		} catch (InterruptedException e) {
			// Ignore.
			return;
		}
	}

	/**
	 * 
	 * @Description: 按照ExecutorService JavaDoc示例代码编写的Graceful Shutdown方法.
	 *               先使用shutdown, 停止接收新任务并尝试完成所有已存在任务. 如果超时, 则调用shutdownNow,
	 *               取消在workQueue中Pending的任务,并中断所有阻塞函数. 如果仍人超時，則強制退出.
	 *               另对在shutdown时线程本身被调用中断做了处理.
	 * @param pool
	 * @param shutdownTimeout
	 * @param shutdownNowTimeout
	 * @param timeUnit
	 */
	public static void gracefulShutdown(ExecutorService pool, int shutdownTimeout, int shutdownNowTimeout,
			TimeUnit timeUnit) {
		// 防止异常时, 线程池为null
		if(pool == null) {
			return;
		}
		
		pool.shutdown(); // Disable new tasks from being submitted
		try {
			// Wait a while for existing tasks to terminate
			if (!pool.awaitTermination(shutdownTimeout, timeUnit)) {
				pool.shutdownNow(); // Cancel currently executing tasks
				// Wait a while for tasks to respond to being cancelled
				if (!pool.awaitTermination(shutdownNowTimeout, timeUnit)) {
					logger.info("Pool did not terminated");
				}
			}
		} catch (InterruptedException ie) {
			// (Re-)Cancel if current thread also interrupted
			pool.shutdownNow();
			// Preserve interrupt status
			Thread.currentThread().interrupt();
		}
	}

	/**
	 * @Description: 直接调用shutdownNow的方法,
	 *               有timeout控制.取消在workQueue中Pending的任务,并中断所有阻塞函数.
	 * @param pool
	 * @param timeout
	 * @param timeUnit
	 */
	public static void normalShutdown(ExecutorService pool, int timeout, TimeUnit timeUnit) {
		try {
			pool.shutdownNow();
			if (!pool.awaitTermination(timeout, timeUnit)) {
				logger.info("Pool did not terminated");
			}
		} catch (InterruptedException ie) {
			Thread.currentThread().interrupt();
		}
	}

}
